<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col :span="7">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="89px">
          <el-form-item label="养殖户" prop="nickName">
            <el-input
              v-model="queryParams.nickName"
              placeholder="请输入养殖户"
              clearable
              size="mini"
              @keyup.enter.native="handleUserQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleUserQuery">搜索</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="17">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="89px">
          <el-form-item label="耳标编号" prop="earNumber">
            <el-input
              v-model="queryParams.earNumber"
              placeholder="请输入耳标编号"
              clearable
              size="mini"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>


    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['dgw:cowEssen:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="5" :xs="24">
        <el-table height="700" :data="deptList"
                  @row-click="selectRow"
                  :row-style="rowStyle"
                  @selection-change="handleSelectionChange">
          <!--      <el-table-column label="养殖用户id" align="center" prop="userId" />-->
          <el-table-column label="乡镇(12)" align="center" prop="deptName"/>
          <el-table-column label="养殖户数量" align="center" prop="userSum"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="small "
                @click="getSum(scope.row)"

              >查看
              </el-button>
              <!--                    <el-button
                                    size="mini"
                                    type="text"
                                    icon="el-icon-delete"
                                    @click="handleDelete(scope.row)"
                                    v-hasPermi="['dgw:vaccine:remove']"
                                  >删除</el-button>-->
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="5" :xs="24">
        <el-table height="700" :data="deptCunList"
                  @row-click="selectRowU"
                  :row-style="rowStyleU"
                  @selection-change="handleSelectionChange">
          <!--      <el-table-column label="养殖用户id" align="center" prop="userId" />-->
          <el-table-column :label=label align="center" prop="village"/>
          <el-table-column label="养殖户数量" align="center" prop="userSum"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="small "
                @click="getUser(scope.row)"

              >查看
              </el-button>
              <!--                    <el-button
                                    size="mini"
                                    type="text"
                                    icon="el-icon-delete"
                                    @click="handleDelete(scope.row)"
                                    v-hasPermi="['dgw:vaccine:remove']"
                                  >删除</el-button>-->
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="6" :xs="24">
        <el-table max-height="700" height="700" :data="CowUserList"
                  @row-click="clickUserButt"
                  :row-style="clickUserStyle"
                  @selection-change="handleSelectionChange">
          <el-table-column label="养殖户" align="center" prop="userName"/>
          <el-table-column label="电话" align="center" prop="phone" width="120"/>
          <el-table-column label="籍贯" align="center" prop="villagesTowns">
            <template slot-scope="scope">
              <span>{{ scope.row.villagesTowns + scope.row.village }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                v-show=" 'userId' in scope.row"
                type="primary"
                size="small "
                @click="getEar(scope.row)"
              >查看
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-table
          v-loading="loading"
          :data="cowEssenList"
          @selection-change="handleSelectionChange"
          max-height="675"
          height="675"
          :default-sort="{prop: 'createTime', order: 'descending'}">
          <!--          <el-table-column type="selection" width="55" align="center" />-->
          <el-table-column label="耳标编号" align="center" prop="earNumber" width="120"/>
          <!--          <el-table-column label="养殖户" align="center" prop="nickName" />-->
          <!--      <el-table-column label="牛信息_主键ID" align="center" prop="cowEssenId" />-->
          <!--      <el-table-column label="地区" align="center" prop="deptName" />-->
          <el-table-column label="体温" align="center" prop="temp">
            <template slot-scope="scope">
              <el-tag effect="dark" size="small"
                      :type="scope.row.temp< 20?'danger': scope.row.temp <=38 && scope.row.temp>=23 ?'primary':'danger'">
                {{ scope.row.temp+'℃' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="计步数据" align="center" prop="jbu"/>

          <!--      <el-table-column label="拆卸状态" align="center" prop="fcai" >
                  <template slot-scope="scope">
                    <el-tag :type="scope.row.fcai==0?'danger':'primary'">
                      {{scope.row.fcai==0?'已拆卸':'未拆卸'}}
                    </el-tag>
                  </template>
                </el-table-column>-->
          <el-table-column label="电池电量" align="center" prop="power" width="80">
            <template slot-scope="scope">
              <el-tag effect="dark" size="medium"
                      :type="scope.row.power >=70?'primary': scope.row.power >= 30 &&scope.row.power<70?'warning':'danger'">
                {{ scope.row.power +'%'}}
              </el-tag>
            </template>
          </el-table-column>
          <!--          <el-table-column label="牛类型" align="center" prop="cowType"  width="80">
                      <template slot-scope="scope">
                        <span>{{scope.row.cowType==1?'育肥牛':scope.row.cowType==2?'牛犊':scope.row.cowType==3?'奶牛':'母牛'}}</span>
                      </template>
                    </el-table-column>-->

          <!--          <el-table-column label="牛棚名称" align="center" prop="cowShedName" width="100"/>-->
          <!--      <el-table-column label="设备mac" align="center" prop="mac" width="170"/>
                <el-table-column label="中继器mac" align="center" prop="devWifiStaMac" width="170" />-->
          <el-table-column label="位置" align="center" prop="shedAddress" min-width="130" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ scope.row.shedAddress + '(' + scope.row.cowShedName + ')' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="时间" align="center" prop="createTime" min-width="150" sortable>
            <template slot-scope="scope">
              <span>{{ scope.row.createTime | formatDate}}</span>
            </template>
          </el-table-column>
          <!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-edit"
                      @click="handleUpdate(scope.row)"
                      v-hasPermi="['dgw:cowEssen:edit']"
                    >修改</el-button>
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-delete"
                      @click="handleDelete(scope.row)"
                      v-hasPermi="['dgw:cowEssen:remove']"
                    >删除</el-button>
                  </template>
                </el-table-column>-->
        </el-table>
      </el-col>
    </el-row>
    <!--    <el-row :gutter="10">
          <el-col :span="7">
            <el-table v-loading="loading"  :data="userList">
              <el-table-column label="养殖户" align="center" prop="nick_name" />
              <el-table-column label="手机号" align="center" prop="user_name" width="110" />
              <el-table-column label="地址" align="center" prop="dept_name"  />
                    <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                     <template slot-scope="scope">
                       <el-button
                         size="mini"
                         type="primary"
                         @click="handlequery(scope.row)"
                       >查询数据</el-button>
                     </template>
                   </el-table-column>
            </el-table>
            <pagination
              v-show="userTotal>0"
              :total="userTotal"
              :page.sync="queryUserParams.pageNum"
              :limit.sync="queryUserParams.pageSize"
              @pagination="getUserList"
            />
          </el-col>
          <el-col :span="17">


          </el-col>
        </el-row>-->


    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <!-- 添加或修改牛信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备mac" prop="mac">
          <el-input v-model="form.mac" placeholder="请输入设备mac"/>
        </el-form-item>
        <el-form-item label="中继器mac" prop="devwifistamac">
          <el-input v-model="form.devwifistamac" placeholder="请输入中继器mac"/>
        </el-form-item>
        <el-form-item label="体温" prop="temp">
          <el-input v-model="form.temp" placeholder="请输入体温"/>
        </el-form-item>
        <el-form-item label="计步数据" prop="jbu">
          <el-input v-model="form.jbu" placeholder="请输入计步数据"/>
        </el-form-item>
        <el-form-item label="耳标编号" prop="earNumber">
          <el-input v-model="form.earNumber" placeholder="请输入耳标编号"/>
        </el-form-item>
        <el-form-item label="牛的具体位置" prop="cowAddress">
          <el-input v-model="form.cowAddress" placeholder="请输入牛的具体位置"/>
        </el-form-item>
        <el-form-item label="拆卸状态(0是未拆.1是已拆)" prop="fcai">
          <el-input v-model="form.fcai" placeholder="请输入拆卸状态(0是未拆.1是已拆)"/>
        </el-form-item>
        <el-form-item label="电池电量" prop="power">
          <el-input v-model="form.power" placeholder="请输入电池电量"/>
        </el-form-item>
        <el-form-item label="牛类型 0为母牛，1为种牛，2为肉牛" prop="cowType">
          <el-select v-model="form.cowType" placeholder="请选择牛类型 0为母牛，1为种牛，2为肉牛">
            <el-option label="请选择字典生成" value=""/>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCowEssen,
  getCowEssen,
  delCowEssen,
  addCowEssen,
  updateCowEssen,
  exportCowEssen,
  listUser
} from "@/api/dgw/cowEssen";
import {formatDate} from "@/utils/date"
import {queryDeptCun} from "@/api/system/dept"
import {listQueryVillage, queryUserName} from "@/api/dgw/registration"

export default {
  name: "CowEssen",
  data() {
    return {
      clickUserButtName: null,
      selectDeptName: null,
      selectDeptNameU: null,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //用户总条数
      userTotal: 0,
      // 牛信息表格数据
      cowEssenList: [],
      deptList: [],
      deptCunList: [],
      //用户信息
      userList: [],
      CowUserList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      label:'村庄(**)',
      // 牛类型 0为母牛，1为种牛，2为肉牛时间范围
      daterangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nickName: null,
        devwifistamac: null,
        earNumber: null,
      },
      queryCunParams: {
        villagesTowns: null
      },
      queryCunUserParams: {
        village: null
      },
      // 查询参数
      queryUserParams: {
        pageNum: 1,
        pageSize: 10,
        nickName: null,
        deptName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        mac: [
          {required: true, message: "设备mac不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getQueryDeptCun();
  },
  filters: {
    formatDate: function (time) {
      let date = new Date(time).getTime()
      let state = new Date().getTime() - 86400000
      if (date >= state) {
        let dateTime = new Date(time)
        return formatDate(dateTime, 'yy-MM-dd hh:mm:ss')
      } else {
        let dateState = new Date().getTime()//当前时间戳
        let dateNow = dateState - date
        var days = parseInt(dateNow / (1000 * 60 * 60 * 24));
        var hours = parseInt((dateNow % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = parseInt((dateNow % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = (dateNow % (1000 * 60)) / 1000;
        return days + " 天 " + hours + " 小时 " + minutes + " 分钟没有上报数据了";
      }
      // let timeData = formatDate(date, 'yy-MM-dd hh:mm:ss')
      //let dataTime = (new Date(timeData)).getTime()

    },
    format(time) {
      let date = new Date(time)

      return date
    }
  },
  methods: {
    date(){
      let state=new Date(new Date().getTime()-1800000)
      let date=new Date(state)
      return date
    },
    rowStyle(row, rowIndex) {
      //
      if (this.selectDeptName === row.row.deptName) {
        return {'background-image': 'linear-gradient(-60deg,#81FFEF 0%,#F067B4 100%)', cursor: 'pointer'};
      }
      return {cursor: 'pointer'};
    },
    rowStyleU({row}) {
      if (this.selectDeptNameU === row.village) {
        return {'background-image': 'linear-gradient(-60deg,#81FFEF 0%,#F067B4 100%)', cursor: 'pointer'};
      }
      return {cursor: 'pointer'};
    },
    clickUserStyle({row}) {
      if (this.clickUserButtName === row.userName) {
        return {'background-image': 'linear-gradient(-60deg,#81FFEF 0%,#F067B4 100%)', cursor: 'pointer'};
      }
      return {cursor: 'pointer'};
    },
    selectRowU(row) {
      this.selectDeptNameU = row.village;
    },
    clickUserButt(row) {
      this.clickUserButtName = row.userName;
    },
    selectRow(row) {
      // console.log("selectRow：",row);
      this.selectDeptName = row.deptName;
    },
    //queryDeptCun
    getQueryDeptCun() {
      this.loading = true;
      queryDeptCun().then(response => {
        console.log("乡镇", response)
        this.deptList = response.data
        this.loading = false;
      })
    },
    getSum(row) {
      this.queryCunParams.villagesTowns = row.deptName
      listQueryVillage(this.queryCunParams).then(response => {
        console.log(response)
        this.label='村庄('+response.total+')'
        this.deptCunList = response.rows
      })
    },
    getUser(row) {
      this.queryCunUserParams.village = row.village
      queryUserName(this.queryCunUserParams).then(response => {
        // console.log("输出resp：",response);
        this.CowUserList = response.data
     /*   response.data.forEach(re=>{
          console.log(re.userName,'userId' in re);
        })*/
      })
    },
    getEar(row) {
      // console.log("输入ROW@@:",row);
      this.queryParams.nickName = row.userName
      this.loading = true;
      //console.log("@@@:",this.queryParams);
      listCowEssen(this.queryParams).then(response => {
        // console.log("牛信息", response);
        this.cowEssenList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询牛信息列表 */

    /** 查询用户信息 */
    getList() {
      this.loading = true;
      listCowEssen(this.queryParams).then(response => {
        console.log("牛信息", response);
        this.cowEssenList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        cowEssenId: null,
        mac: null,
        devwifistamac: null,
        temp: null,
        jbu: null,
        earNumber: null,
        cowAddress: null,
        fcai: null,
        createTime: null,
        power: null,
        cowType: null,
        userId: null,
        enterpriseId: null
      };
      this.resetForm("form");
    },
    /*  /!** 搜索按钮操作 *!/
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },*/
    handleUserQuery(row) {
      console.log("查询", row)
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.cowEssenList = [];
      this.handleUserQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.cowEssenId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加牛信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const cowEssenId = row.cowEssenId || this.ids
      getCowEssen(cowEssenId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改牛信息";
      });
    },
    /** 查询数据*/
    handleQuery(row) {
      this.reset();
      const nickName = row.nick_name;
      this.queryParams.nickName = nickName;
      this.getList();

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.cowEssenId != null) {
            updateCowEssen(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCowEssen(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const cowEssenIds = row.cowEssenId || this.ids;
      this.$modal.confirm('是否确认删除牛信息编号为"' + cowEssenIds + '"的数据项？').then(function () {
        return delCowEssen(cowEssenIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$modal.confirm('是否确认导出所有牛信息数据项？').then(() => {
        this.exportLoading = true;
        return exportCowEssen(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {
      });
    }
  }
};
</script>
